import axios from "axios"
import { ElMessage } from "element-plus"
import bus from "vue3-eventbus"

const request = axios.create({
  baseURL: `${import.meta.env.VITE_APP_URL}`,
  timeout: 5000,
  headers: {
    Authorization: null,
  },
})

request.interceptors.request.use(
  (res) => {
    if (localStorage.getItem("TOKEN")) {
      res.headers.Authorization = localStorage.getItem("TOKEN")
    }
    return res
  },
  (err) => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  (res) => {
    if (res.data.code === 401) {
      localStorage.clear()
      sessionStorage.clear()
      bus.emit('userNoLogin')
    } else if (res.data.code && res.data.code !== 200) {
      ElMessage.error(res.data.msg)
    }
    return res
  },
  (err) => {
    return Promise.reject(err)
  }
)

export default request
